package cn.edu.zut.internship.web.controller.sys;


import cn.edu.zut.internship.bean.sys.Result;
import cn.edu.zut.internship.bean.sys.SysUser;
import cn.edu.zut.internship.entity.AuthSysMenu;
import cn.edu.zut.internship.entity.AuthSysUser;
import cn.edu.zut.internship.iservice.sys.IAuthService;
import cn.edu.zut.internship.iservice.sys.IRoleService;
import cn.edu.zut.internship.iservice.sys.IUserService;
import cn.edu.zut.internship.iservice.teach.TeachSV;
import cn.edu.zut.internship.web.utils.EncryptUtil;
import cn.edu.zut.internship.web.utils.JwtUtil;
import cn.edu.zut.internship.web.utils.RedisUtils;

import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/auth")

public class AuthController {
    @Reference(retries = 0,timeout = 3000)
    private IAuthService authService;
    @Reference(retries = 0,timeout = 3000)
    private IUserService userService;
    @Reference(retries = 0,timeout = 3000)
    private IRoleService roleService;
    @Reference(retries = 0,timeout = 3000)
    private TeachSV teachSV;
    @Autowired
    private RedisUtils redisUtils;
    @GetMapping("/search/{mnName}")
    public Result getOperateMenuRoleIds(@PathVariable("mnName") String mnName){
        Result result = new Result();
        List<Long> idList = this.roleService.searchMenuRoleIds(mnName);
        result.setBeans(idList);
        return result;
    }

    /**
     * 获取系统所有路由表
     * @return
     */
    @GetMapping("/routes")
    public Result getMenu(){
        Result result = new Result();
        List<AuthSysMenu> menuList = authService.getMenus();
        result.setBeans(menuList);
        return result;
    }
    @PostMapping("/login")
    public Result login(@RequestBody Map params){
        String userAccount = (String) params.get("username");
        String password = (String) params.get("password");
        Result result = new Result();
        // 1 从Shiro框架中，获取一个Subject对象，代表当前会话的用户
        Subject subject = SecurityUtils.getSubject();
        // 2 认证subject的身份
        // 2.1 封装要认证的身份信息
        String md5Str = EncryptUtil.getMD5Str(password);
//        AuthenticationToken token = new UsernamePasswordToken(userName, EncryptUtil.getMD5Str(password));
        AuthenticationToken token = new UsernamePasswordToken(userAccount, password);
        // 2.2 认证：认证失败，抛异常
        try {
            subject.login(token);
            //将用户信息放入Session中
            SysUser sysUserInfo = userService.getSysUserInfo(userAccount);
            Session session = subject.getSession();
            session.setAttribute("userInfo",sysUserInfo);
            String resToken = JwtUtil.sign(userAccount);
            result.getBean().put("resToken",resToken);
//            this.redisUtil.set(resToken, userName,30*60);
        }catch(Exception e){
            e.printStackTrace();
            result.setMessage("用户名或密码错误");
            result.setCode(-9999);
            return result;
        }
        result.setCode(20000);
        return result;
    }
    @GetMapping("/login")
    public void loginPage(HttpServletResponse res){
        try {
            res.sendRedirect("http://localhost:9527");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("/noLogin")
    public Result noLogin(){
        Result result = new Result();
        result.setCode(20001);
        result.setMessage("没有登录，请登录先");
        return result;
    }

    @RequestMapping("/noAuth")
    public Result noAuth(){
        Result result = new Result();
        result.setCode(20002);
        result.setMessage("没有权限访问");
        return result;
    }

    @GetMapping("/info")
    public Result info(@RequestHeader("X-Token") String token){
        Result result = new Result();
        String userName = null;
        try {
            userName = JwtUtil.verityToken(token, "loginName");

        }catch (Exception e) {
            result.setCode(-99999);
           result.setMessage("登录过期，请重新登录");
        }
        if(userName == null){
            throw new RuntimeException("没有登录");
        }else{
//            AuthSysUser user = userService.findByUserName(userName);
            SysUser sysUser = userService.getSysUserByAccount(userName);
            if(sysUser == null){
                throw new RuntimeException("没有登录");
            }else{
                result.getBean().put("user",sysUser);
            }
        }
        return result;
    }
    @PostMapping("/logout")
    public Result logOut(@RequestHeader("X-Token") String token){
        Result result = new Result();
        // 1 从Shiro框架中，获取一个Subject对象，代表当前会话的用户
        Subject subject = SecurityUtils.getSubject();
        //退出登录
        subject.logout();
        //session.removeAttribute(token);
        //session.invalidate();
//        SecurityUtils.getSubject().logout();
        // 删除redis中的标记
//        this.redisUtil.del(token);
        return result;
    }
}
